<template>
  <div class="container dark-theme">
    <!-- 头部导航栏 -->
    <div class="header">
      <div class="back-button" @click="goBack">
        <i class="el-icon-arrow-left"></i> 返回
      </div>
      <div class="title">商品详情</div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <el-spinner></el-spinner>
      <span>加载中...</span>
    </div>

    <!-- 错误提示 -->
    <div v-else-if="error" class="error">
      <p>{{ error }}</p>
      <el-button type="primary" @click="fetchProductDetail">重试</el-button>
    </div>

    <!-- 主要内容区域 -->
    <div v-else class="main-content">
      <div class="product-info">
        <div class="product-image">
          <img :src="product.images || defaultImage" :alt="product.title">
        </div>
        <div class="product-details">
          <h2>{{ product.title }}</h2>
          <h3>{{ product.subTitle }}</h3>
          <div class="price">
            ¥{{ (product.currentPrice / 100).toFixed(2) }}
            <span class="original-price" v-if="product.originalPrice > product.currentPrice">
              ¥{{ (product.originalPrice / 100).toFixed(2) }}
            </span>
          </div>
          <div class="stock">库存：{{ product.stock }}件</div>
          <div class="store-info">
            <i class="el-icon-shop"></i>
            <span>{{ product.shopName || '未知店铺' }}</span>
          </div>
          <div class="tags">
            <span v-if="product.currentPrice < product.originalPrice" class="tag special">特价</span>
            <span v-if="isNewProduct(product.createTime)" class="tag new">新品</span>
            <span v-if="product.stock > 0 && product.status === 1" class="tag hot">热销</span>
          </div>
          <!-- 数量选择器 -->
          <div class="quantity-selector">
            <label>购买数量：</label>
            <el-input-number
              v-model="quantity"
              :min="1"
              :max="product.stock"
              size="small"
              @change="handleQuantityChange"
            ></el-input-number>
          </div>
        </div>
      </div>

      <!-- 商品描述 -->
      <div class="description-section">
        <h3>商品描述</h3>
        <p>{{ product.description || '暂无描述' }}</p>
      </div>

      <!-- 购买按钮 -->
      <div class="purchase-actions">
        <el-button
          type="danger"
          @click="buyNow"
          :disabled="product.status !== 1 || product.stock <= 0 || quantity <= 0"
        >
          立即购买
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'ProductDetail',
  data() {
    return {
      product: {
        id: null,
        title: '',
        subTitle: '',
        description: '',
        currentPrice: 0,
        originalPrice: 0,
        images: '',
        shopId: null,
        shopName: '',
        stock: 0,
        status: 0,
        createTime: ''
      },
      defaultImage: 'https://via.placeholder.com/150',
      imageBaseUrl: 'http://localhost:8089',
      loading: false,
      error: null,
      quantity: 1 // 默认购买数量
    };
  },
  created() {
    this.fetchProductDetail();
  },
  methods: {
    async fetchProductDetail() {
      this.loading = true;
      this.error = null;
      try {
        const goodId = this.$route.params.id;
        const response = await axios.get(`/commodity/good/goodInfo/${goodId}`);
        if (response.data.success) {
          const productData = Array.isArray(response.data.data)
            ? response.data.data[0]
            : response.data.data;
          if (!productData) {
            throw new Error('商品数据为空');
          }

          // 获取店铺名称
          let shopName = '未知店铺';
          try {
            const shopResponse = await axios.get(`/commodity/shop/${productData.shopId}`);
            if (shopResponse.data.success && shopResponse.data.data) {
              shopName = shopResponse.data.data.name || `店铺${productData.shopId}`;
            }
          } catch (shopError) {
            console.error('获取店铺信息失败:', shopError);
          }

          this.product = {
            ...productData,
            images: productData.images
              ? productData.images.startsWith('http')
                ? productData.images
                : `${this.imageBaseUrl}${productData.images}`
              : this.defaultImage,
            shopName
          };
          // 重置数量选择器，确保不超过库存
          this.quantity = Math.min(this.quantity, this.product.stock);
        } else {
          this.error = response.data.errorMsg || '获取商品详情失败';
        }
      } catch (error) {
        this.error = error.message || '网络错误，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    handleQuantityChange(value) {
      if (value > this.product.stock) {
        this.$message.warning(`购买数量不能超过库存（${this.product.stock}件）`);
        this.quantity = this.product.stock;
      } else if (value < 1) {
        this.$message.warning('购买数量不能小于1');
        this.quantity = 1;
      }
    },
    async buyNow() {
      try {
        // 检查库存和状态
        if (this.product.status !== 1) {
          this.$message.warning('商品已下架，无法购买');
          return;
        }
        if (this.product.stock <= 0) {
          this.$message.warning('库存不足，无法购买');
          return;
        }
        if (this.quantity > this.product.stock) {
          this.$message.warning(`购买数量不能超过库存（${this.product.stock}件）`);
          return;
        }

        // 获取用户信息
        const { data: userData } = await axios.get('/users/user/basic', {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        });

        if (userData.success && userData.data) {
          this.user = userData.data;
        } else {
          this.$message.error('获取用户信息失败：无有效数据');
          return;
        }

        const userId = this.user.id;
        const goodId = this.$route.params.id;

        if (!goodId) {
          this.$message.error('商品ID无效');
          return;
        }

        // 发送购买请求，传递数量
        const { data } = await axios.post(
          `/commodity/good-order/goodInfo/${goodId}?userId=${userId}&amount=${this.quantity}`,
          {},
          { headers: { Authorization: `Bearer ${localStorage.getItem('token')}` } }
        );

        if (data.success) {
          this.$message.success(`抢购成功，订单ID：${data.data}`);
          // 购买成功后刷新商品详情以更新库存
          await this.fetchProductDetail();
          // 重置数量选择器
          this.quantity = 1;
        } else {
          this.$message.error(data.errorMsg || '抢购失败');
        }
      } catch (error) {
        this.$message.error('请求失败：' + (error.response?.data?.errorMsg || error.message));
      }
    },
    isNewProduct(createTime) {
      if (!createTime) return false;
      const createDate = new Date(createTime);
      const now = new Date();
      const diffDays = (now - createDate) / (1000 * 60 * 60 * 24);
      return diffDays <= 7;
    }
  }
};
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: radial-gradient(ellipse at center, #001e3c 0%, #000 100%);
  color: #fff;
  font-family: 'Microsoft YaHei', sans-serif;
}

.header {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #002d52;
}

.back-button {
  cursor: pointer;
  color: #999;
  font-size: 16px;
}

.back-button:hover {
  color: #4fc3f7;
}

.title {
  margin-left: 20px;
  font-size: 20px;
  font-weight: bold;
}

.main-content {
  padding: 20px;
}

.product-info {
  background: rgba(0, 45, 82, 0.8);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.product-image {
  width: 100%;
  max-width: 400px;
  height: 300px;
}

.product-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
}

.product-details {
  flex: 1;
}

.product-details h2 {
  margin: 0 0 10px 0;
  color: #fff;
}

.product-details h3 {
  margin: 0 0 10px 0;
  color: #e0e0e0;
  font-size: 18px;
}

.price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.original-price {
  color: #b0bec5;
  font-size: 16px;
  text-decoration: line-through;
  margin-left: 10px;
}

.stock {
  color: #e0e0e0;
  margin-bottom: 10px;
}

.store-info {
  color: #b0bec5;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}

.store-info i {
  margin-right: 5px;
}

.tags {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.tag.special {
  background: #f56c6c;
  color: #fff;
}

.tag.new {
  background: #67c23a;
  color: #fff;
}

.tag.hot {
  background: #e6a23c;
  color: #fff;
}

.quantity-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 20px;
}

.quantity-selector label {
  color: #e0e0e0;
  font-size: 16px;
}

.description-section {
  background: rgba(0, 45, 82, 0.8);
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.description-section h3 {
  margin: 0 0 10px 0;
  color: #fff;
}

.description-section p {
  color: #e0e0e0;
  line-height: 1.6;
  margin: 0;
}

.purchase-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.el-button {
  padding: 12px 30px;
}

.el-button--primary {
  background: #003b64;
  border: 1px solid #4fc3f7;
  color: #4fc3f7;
}

.el-button--primary:hover:not(:disabled) {
  background: #4fc3f7;
  color: #fff;
}

.el-button--danger {
  background: #f56c6c;
  border: 1px solid #f56c6c;
  color: #fff;
}

.el-button--danger:hover:not(:disabled) {
  background: #f78989;
  border-color: #f78989;
}

.el-button:disabled {
  background: #909399;
  border-color: #909399;
  color: #fff;
  cursor: not-allowed;
}

.loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  color: #4fc3f7;
}

.error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 50vh;
  color: #f56c6c;
}

.error p {
  margin-bottom: 20px;
}
</style>

